import React,{useState,useEffect, useRef} from 'react'
import './index.css'


function DragwidthCom (props) {
    let {flexBasis=300,direction = 'row'} = props
    const dragwidthcomBoxRef = useRef()
    const leftRef = useRef()
    const lineRef = useRef()
    useEffect(() =>{
        const dragwidthcomBoxDom = dragwidthcomBoxRef.current
        const leftDom = leftRef.current
        const lineDom = lineRef.current
        let isMousedown = false
        const offsetTotal = {x:0,y:0}
        const startPosition = {x:0,y:0}
        lineDom.addEventListener('mousedown',(e)=>{
            isMousedown = true
            startPosition.x = e.clientX
            startPosition.y = e.clientY
        })
        lineDom.addEventListener('mouseup',(e)=>{
            isMousedown = false
        })
        document.addEventListener('mousemove',(e)=>{
            if (isMousedown) {
                offsetTotal.x += e.clientX - startPosition.x
                offsetTotal.y += e.clientY - startPosition.y
                startPosition.x = e.clientX
                startPosition.y = e.clientY  
                leftDom.style.flexBasis = flexBasis  + (direction ==='row' ?  offsetTotal.x : offsetTotal.y)  + 'px'    
            }
        })

    },[])

    return (
        <div className='dragwidthcomBox' ref={dragwidthcomBoxRef} style={{flexDirection: direction}}>
            <div className='left' ref={leftRef}>left</div>
            <div className='line' draggable={false} ref={lineRef} style={{cursor: direction ==='row' ? 'e-resize' :'n-resize'}}></div>
            <div className='right'>right</div>
        </div>
    )
}

export default DragwidthCom